<template>
  <div class="cart-page">
    <div class="container">
      <div class="page-header">
        <h1>购物车</h1>
        <div class="cart-summary">
          <span>共 {{ totalItems }} 件商品</span>
        </div>
      </div>

      <div v-if="cartItems.length > 0" class="cart-content">
        <!-- 购物车商品列表 -->
        <div class="cart-main">
          <div class="cart-header">
            <el-checkbox 
              v-model="selectAll"
              @change="handleSelectAll"
              :indeterminate="isIndeterminate"
            >
              全选
            </el-checkbox>
            <span class="header-item">商品信息</span>
            <span class="header-item">单价</span>
            <span class="header-item">数量</span>
            <span class="header-item">小计</span>
            <span class="header-item">操作</span>
          </div>

          <div class="cart-items">
            <div 
              v-for="item in cartItems"
              :key="`${item.id}-${item.variant?.id || 'default'}`"
              class="cart-item"
            >
              <div class="item-select">
                <el-checkbox 
                  v-model="item.selected"
                  @change="updateSelection"
                />
              </div>

              <div class="item-info">
                <div class="item-image">
                  <img :src="item.image" :alt="item.name" />
                </div>
                <div class="item-details">
                  <h3 class="item-name">{{ item.name }}</h3>
                  <p v-if="item.variant" class="item-variant">
                    规格：{{ item.variant.name }}
                  </p>
                  <p class="item-description">{{ item.description }}</p>
                </div>
              </div>

              <div class="item-price">
                <span class="current-price">¥{{ item.price }}</span>
                <span v-if="item.originalPrice" class="original-price">
                  ¥{{ item.originalPrice }}
                </span>
              </div>

              <div class="item-quantity">
                <el-input-number
                  v-model="item.quantity"
                  :min="1"
                  :max="99"
                  @change="updateQuantity(item)"
                  size="small"
                />
              </div>

              <div class="item-subtotal">
                <span class="subtotal-price">
                  ¥{{ (item.price * item.quantity).toFixed(2) }}
                </span>
              </div>

              <div class="item-actions">
                <el-button 
                  type="danger" 
                  text
                  @click="removeItem(item)"
                  :icon="Delete"
                >
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 购物车底部操作栏 -->
        <div class="cart-footer">
          <div class="footer-left">
            <el-checkbox 
              v-model="selectAll"
              @change="handleSelectAll"
              :indeterminate="isIndeterminate"
            >
              全选
            </el-checkbox>
            
            <el-button 
              type="danger" 
              text
              @click="removeSelected"
              :disabled="selectedItems.length === 0"
            >
              删除选中商品
            </el-button>
            
            <el-button 
              text
              @click="clearCart"
              :disabled="cartItems.length === 0"
            >
              清空购物车
            </el-button>
          </div>

          <div class="footer-right">
            <div class="price-summary">
              <div class="summary-line">
                <span>已选商品 {{ selectedItems.length }} 件</span>
              </div>
              <div class="summary-line total">
                <span>合计：</span>
                <span class="total-price">¥{{ selectedTotal.toFixed(2) }}</span>
              </div>
              <div v-if="savedAmount > 0" class="summary-line saved">
                <span>已省：¥{{ savedAmount.toFixed(2) }}</span>
              </div>
            </div>

            <el-button 
              type="primary" 
              size="large"
              @click="goToCheckout"
              :disabled="selectedItems.length === 0"
              class="checkout-btn"
            >
              去结算 ({{ selectedItems.length }})
            </el-button>
          </div>
        </div>

        <!-- 推荐商品 -->
        <div class="recommendations">
          <h2 class="section-title">猜你喜欢</h2>
          <div class="recommendations-grid">
            <ProductCard 
              v-for="product in recommendedProducts"
              :key="product.id"
              :product="product"
            />
          </div>
        </div>
      </div>

      <!-- 空购物车 -->
      <div v-else class="empty-cart">
        <el-empty description="购物车是空的">
          <div class="empty-actions">
            <el-button type="primary" @click="$router.push('/products')">
              去购物
            </el-button>
            <el-button @click="$router.push('/')">
              返回首页
            </el-button>
          </div>
        </el-empty>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { store } from '@/store'
import { ElMessage, ElMessageBox } from 'element-plus'
import ProductCard from '@/components/ProductCard.vue'
import { Delete } from '@element-plus/icons-vue'

export default {
  name: 'ShoppingCart',
  components: {
    ProductCard,
    Delete
  },
  setup() {
    const router = useRouter()
    
    // 购物车数据
    const cartItems = computed(() => {
      return store.cart.items.map(item => ({
        ...item,
        selected: item.selected !== false // 默认选中
      }))
    })
    
    // 推荐商品
    const recommendedProducts = ref([
      {
        id: 7,
        name: '高级狗粮 鸡肉味',
        description: '优质蛋白质，均衡营养',
        price: 256,
        originalPrice: 320,
        image: require('@/assets/images/AD0I9ruEDBAEGAAgy4rB_wUo_uOp2AUwgAY4gAY_400x400.png'),
        category: 'food'
      },
      {
        id: 8,
        name: '宠物训练器',
        description: '声光训练，培养良好习惯',
        price: 156,
        image: require('@/assets/images/AD0I9ruEDBAEGAAgyfLF_wUo-KfRgAIwgAY4gAY_400x400.png'),
        category: 'toys'
      },
      {
        id: 9,
        name: '宠物美容工具套装',
        description: '专业美容，在家也能给宠物做造型',
        price: 89,
        image: require('@/assets/images/AD0I9ruEDBAEGAAgz_7F_wUo9NDVhgQwgAY4gAY_400x400.png'),
        category: 'care'
      },
      {
        id: 10,
        name: '宠物外出背包',
        description: '透气舒适，出行必备',
        price: 128,
        image: require('@/assets/images/AD0I9ruEDBAEGAAgvIvB_wUo1rTt_AYwgAY4gAY_400x400.png'),
        category: 'accessories'
      }
    ])
    
    // 计算属性
    const totalItems = computed(() => {
      return cartItems.value.reduce((total, item) => total + item.quantity, 0)
    })
    
    const selectedItems = computed(() => {
      return cartItems.value.filter(item => item.selected)
    })
    
    const selectedTotal = computed(() => {
      return selectedItems.value.reduce((total, item) => {
        return total + (item.price * item.quantity)
      }, 0)
    })
    
    const savedAmount = computed(() => {
      return selectedItems.value.reduce((total, item) => {
        const originalPrice = item.originalPrice || item.price
        return total + ((originalPrice - item.price) * item.quantity)
      }, 0)
    })
    
    const selectAll = computed({
      get() {
        return cartItems.value.length > 0 && cartItems.value.every(item => item.selected)
      },
      set(value) {
        cartItems.value.forEach(item => {
          item.selected = value
        })
      }
    })
    
    const isIndeterminate = computed(() => {
      const selectedCount = cartItems.value.filter(item => item.selected).length
      return selectedCount > 0 && selectedCount < cartItems.value.length
    })
    
    // 方法
    const handleSelectAll = (value) => {
      cartItems.value.forEach(item => {
        item.selected = value
      })
    }
    
    const updateSelection = () => {
      // 触发响应式更新
    }
    
    const updateQuantity = (item) => {
      const cartItem = store.cart.items.find(cartItem => 
        cartItem.id === item.id && 
        (cartItem.variant?.id || 'default') === (item.variant?.id || 'default')
      )
      
      if (cartItem) {
        store.updateQuantity(cartItem.id, item.quantity)
      }
    }
    
    const removeItem = async (item) => {
      try {
        await ElMessageBox.confirm(
          '确定要从购物车中删除这件商品吗？',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        store.removeFromCart(item.id)
        ElMessage.success('商品已从购物车中删除')
      } catch {
        // 用户取消删除
      }
    }
    
    const removeSelected = async () => {
      if (selectedItems.value.length === 0) {
        ElMessage.warning('请选择要删除的商品')
        return
      }
      
      try {
        await ElMessageBox.confirm(
          `确定要删除选中的 ${selectedItems.value.length} 件商品吗？`,
          '批量删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        selectedItems.value.forEach(item => {
          store.removeFromCart(item.id)
        })
        
        ElMessage.success(`已删除 ${selectedItems.value.length} 件商品`)
      } catch {
        // 用户取消删除
      }
    }
    
    const clearCart = async () => {
      try {
        await ElMessageBox.confirm(
          '确定要清空购物车吗？此操作不可恢复。',
          '清空购物车',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        store.clearCart()
        ElMessage.success('购物车已清空')
      } catch {
        // 用户取消清空
      }
    }
    
    const goToCheckout = () => {
      if (selectedItems.value.length === 0) {
        ElMessage.warning('请选择要结算的商品')
        return
      }
      
      // 将选中的商品信息传递给结算页面
      const checkoutItems = selectedItems.value.map(item => ({
        ...item,
        subtotal: item.price * item.quantity
      }))
      
      // 可以通过路由状态传递数据
      router.push({
        path: '/checkout',
        state: { checkoutItems }
      })
    }
    
    // 监听购物车变化，自动保存选中状态
    watch(cartItems, (newItems) => {
      newItems.forEach((item, index) => {
        const storeItem = store.cart.items[index]
        if (storeItem) {
          storeItem.selected = item.selected
        }
      })
    }, { deep: true })
    
    return {
      cartItems,
      recommendedProducts,
      totalItems,
      selectedItems,
      selectedTotal,
      savedAmount,
      selectAll,
      isIndeterminate,
      handleSelectAll,
      updateSelection,
      updateQuantity,
      removeItem,
      removeSelected,
      clearCart,
      goToCheckout,
      // Element Plus icons
      Delete
    }
  }
}
</script>

<style scoped>
.cart-page {
  min-height: 100vh;
  background: #f8f9fa;
  padding: 30px 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 30px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.page-header h1 {
  font-size: 2rem;
  color: #333;
}

.cart-summary {
  color: #666;
  font-size: 1.1rem;
}

.cart-content {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.cart-main {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.cart-header {
  display: grid;
  grid-template-columns: 50px 1fr 120px 150px 120px 80px;
  gap: 20px;
  align-items: center;
  padding: 20px 30px;
  background: #f8f9fa;
  border-bottom: 1px solid #eee;
  font-weight: 500;
  color: #333;
}

.header-item {
  text-align: center;
}

.cart-items {
  display: flex;
  flex-direction: column;
}

.cart-item {
  display: grid;
  grid-template-columns: 50px 1fr 120px 150px 120px 80px;
  gap: 20px;
  align-items: center;
  padding: 25px 30px;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.3s ease;
}

.cart-item:hover {
  background: #fafafa;
}

.cart-item:last-child {
  border-bottom: none;
}

.item-select {
  display: flex;
  justify-content: center;
}

.item-info {
  display: flex;
  gap: 15px;
  align-items: center;
}

.item-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  overflow: hidden;
  flex-shrink: 0;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-details {
  flex: 1;
  min-width: 0;
}

.item-name {
  font-size: 1.1rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item-variant {
  font-size: 0.9rem;
  color: #666;
  margin-bottom: 5px;
}

.item-description {
  font-size: 0.9rem;
  color: #999;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item-price {
  text-align: center;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.current-price {
  font-size: 1.1rem;
  font-weight: 600;
  color: #f56565;
}

.original-price {
  font-size: 0.9rem;
  color: #999;
  text-decoration: line-through;
}

.item-quantity {
  display: flex;
  justify-content: center;
}

.item-subtotal {
  text-align: center;
}

.subtotal-price {
  font-size: 1.2rem;
  font-weight: 600;
  color: #333;
}

.item-actions {
  display: flex;
  justify-content: center;
}

.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 25px 30px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.footer-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.footer-right {
  display: flex;
  align-items: center;
  gap: 30px;
}

.price-summary {
  text-align: right;
}

.summary-line {
  margin-bottom: 8px;
  color: #666;
}

.summary-line.total {
  font-size: 1.2rem;
  color: #333;
}

.total-price {
  font-size: 1.5rem;
  font-weight: bold;
  color: #f56565;
  margin-left: 10px;
}

.summary-line.saved {
  color: #FFB300;
  font-size: 0.9rem;
}

.checkout-btn {
  height: 50px;
  padding: 0 30px;
  font-size: 1.1rem;
}

/* 推荐商品 */
.recommendations {
  background: white;
  padding: 40px 30px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.section-title {
  font-size: 1.5rem;
  color: #333;
  margin-bottom: 25px;
  text-align: center;
}

.recommendations-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

/* 空购物车 */
.empty-cart {
  background: white;
  padding: 60px 30px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  text-align: center;
}

.empty-actions {
  display: flex;
  gap: 15px;
  justify-content: center;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .cart-header,
  .cart-item {
    grid-template-columns: 40px 1fr 100px 120px 100px 70px;
    gap: 15px;
    padding: 20px;
  }
  
  .item-image {
    width: 60px;
    height: 60px;
  }
  
  .footer-right {
    gap: 20px;
  }
}

@media (max-width: 768px) {
  .cart-page {
    padding: 20px 0;
  }
  
  .page-header {
    flex-direction: column;
    gap: 15px;
    text-align: center;
    padding: 25px 20px;
  }
  
  .cart-header {
    display: none; /* 隐藏表头 */
  }
  
  .cart-item {
    display: flex;
    flex-direction: column;
    gap: 15px;
    padding: 20px;
    align-items: stretch;
  }
  
  .item-info {
    order: 1;
  }
  
  .item-select {
    order: 0;
    align-self: flex-start;
  }
  
  .item-price,
  .item-quantity,
  .item-subtotal {
    order: 2;
    display: flex;
    justify-content: space-between;
    align-items: center;
    text-align: left;
  }
  
  .item-price::before {
    content: '单价：';
    color: #666;
  }
  
  .item-quantity::before {
    content: '数量：';
    color: #666;
  }
  
  .item-subtotal::before {
    content: '小计：';
    color: #666;
  }
  
  .item-actions {
    order: 3;
    justify-content: flex-start;
  }
  
  .cart-footer {
    flex-direction: column;
    gap: 20px;
    padding: 20px;
  }
  
  .footer-left,
  .footer-right {
    width: 100%;
    justify-content: center;
  }
  
  .footer-left {
    flex-wrap: wrap;
    gap: 15px;
  }
  
  .checkout-btn {
    width: 100%;
  }
  
  .recommendations {
    padding: 30px 20px;
  }
  
  .recommendations-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 480px) {
  .item-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .item-image {
    width: 80px;
    height: 80px;
    align-self: center;
  }
  
  .empty-actions {
    flex-direction: column;
    align-items: center;
  }
  
  .empty-actions .el-button {
    width: 200px;
  }
}
</style>
